﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace VerficationsWPF.Verifications
{
    /// <summary>
    /// ReturnTaskWindow.xaml 的交互逻辑
    /// </summary>
    public partial class TaskWindow : Window
    {
        public Func<object> MainTask = default!;

        public Action? FailTask;

        public object? Result;

        public int Timeout = 60;

        public string ExitMessage = "unfinished";

        public bool AutoCloseWindow = true;

        CancellationTokenSource cts = new CancellationTokenSource();

        public TaskWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Result = null;
            TaskFactory taskFactory = new TaskFactory(cts.Token);
            taskFactory.StartNew(() =>
            {
                // 等等窗体显示
                Thread.Sleep(1000);

                // 为避免主任务为空，所以进行了检测。
                if (MainTask == null)
                {
                    Result = null;
                    ExitMessage = "MainTask is null.";
                    return;
                }

                // 如果不加可能会出现因窗体关闭后发生数据交互导致的错误。
                try
                {
                    var res = taskFactory.StartNew(MainTask);
                    if (res.Wait((Timeout - 1) * 1000)) // 开始休眠了1秒
                    {
                        Result = res.Result;
                    }
                    else if (cts.IsCancellationRequested)
                    {
                        ExitMessage = "Cancelled";
                    }
                    else
                    {
                        ExitMessage = "Timeout";
                    }

                }
                catch (Exception ex)
                {
                    Result = null;
                    ExitMessage = "Error: " + ex.Message;
                }

                if (Result == null && FailTask != null)
                    new TaskFactory().StartNew(FailTask).Wait(1000);

                // 如果设置为自动关闭窗体，则会调用Close方法，但由于此时窗体可能已经关闭或其他未知原因，所以用try-catch更为安全
                if (AutoCloseWindow)
                {
                    this.Dispatcher.Invoke(() =>
                    {
                        try
                        {
                            Close();
                        }
                        catch { }
                    });
                }
            });

            // 测试功能，用于显示倒记时的数字
            Task.Run(() =>
            {
                try
                {

                    var endTime = DateTime.Now.AddSeconds(Timeout);
                    while (DateTime.Now < endTime)
                    {
                        var ts = endTime - DateTime.Now;
                        if (ts.TotalSeconds < 0)
                        {
                            Dispatcher.Invoke(() => info.Content = $"Time up");
                            break;
                        }
                        else
                        {
                            Dispatcher.Invoke(() => info.Content = $"If not compeleted, I will close after {ts.TotalSeconds:0.0} seconds.");
                        }
                        Thread.Sleep(100);
                    }
                }
                catch (Exception ex)
                {
                    ExitMessage = "Error: " + ex.Message;
                }
            });
        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            ExitMessage = "Cancelled";
            cts.Cancel();
            Close();
        }
    }
}
